<?php

// $Id$

require_once('te_tree_menu_item.class.php');
require_once('te_tree_menu_item_already_exists.class.php');
require_once('te_tree_menu_item_not_exists.class.php');


class Tree_Menu_Item extends Tangra_Class {
	private $id;
	private $hid;
	private $parent;
	private $label;
	private $link = '';
	private $target = '';
	private $order = 10;
	protected $subitems = array();


	public function set_id($id) {
		tangra_if_not_int_throw_e($id);

		$this->id = $id;
	}


	public function get_id() {
		return $this->id;
	}


	public function set_hid($hid) {
		if (ereg("^[a-z]{1}[a-z0-9_]{0,100}$", $hid)) {
			$this->hid = $hid;
		} else {
			throw TE_Tree_Menu('Invalid hid: '.$hid.'. Must conform ereg("^[a-z]{1}[a-z0-9_]{0,100}$").');
		}
	}


	public function get_hid() {
		return $this->hid;
	}



	public function set_parent($parent) {
		tangra_if_not_int_throw_e($parent);

		$this->parent = $parent;
	}


	public function get_parent() {
		return $this->parent;
	}

	public function set_label($label) {
		$this->label = $label;
	}


	public function get_label() {
		return $this->label;
	}


	public function set_link($link) {
		$this->link = $link;
	}


	public function get_link() {
		return $this->link;
	}


	public function set_target($target) {
		$this->target = $target;
	}


	public function get_target() {
		return $this->target;
	}


	public function set_order($order) {
		tangra_if_not_int_throw_e($order);

		$this->order = $order;
	}


	public function get_order() {
		return $this->order;
	}



	public function set_subitems($subitems) {
		if (is_array($subitems)) {
			foreach($subitems as $item) {
				$this->add_subitem($item);
			}
		} else {
			throw new TE_Tree_Menu_Item('$subitems is not an array.');
		}
	}


	public function add_subitem(Tree_Menu_Item $item) {
		if (!$this->subitem_exists($item)) {
			$this->subitems[$item->get_hid()] = $item;
		} else {
			throw new TE_Tree_Menu_Item_Already_Exists($item->get_hid());
		}
	}


	public function get_subitems() {
		return $this->subitems;
	}


	public static function create_from_import_data($raw_arr, $table = 'menu') {
		$ret = false;

		if (count($raw_arr) == 6) {
			$tmp = new Tree_Menu_Item_DBC($table);
			$tmp->set_label($raw_arr[0]);
			$tmp->set_link($raw_arr[2]);
			$tmp->set_hid($raw_arr[3]);
			$tmp->set_target($raw_arr[4]);
			$tmp->set_order($raw_arr[5]);

			$ret['parent_hid'] = $raw_arr[1];
			$ret['item'] = clone $tmp;
		}

		return $ret;
	}


	public function subitem_exists(Tree_Menu_Item $item) {
		return array_key_exists($item->get_hid(), $this->subitems);
	}
}